package com.kzw.web;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kzw.entity.Dictionary;
import com.kzw.json.Jackson;

import my.db.QueryHelper;
import my.mvc.RequestContext;
import my.util.ResponseUtils;

public class MyAction {

	// 普通表单提交
	public void login1(RequestContext rc) throws Exception {
		String uname = rc.param("uname");
		String passwd = rc.param("passwd");
		System.out.println(uname + ", " + passwd);
		
		// 页面跳转（携带数据）
		rc.reqAttr("name", uname);
		rc.forward("/success.jsp");
	}
	
	// ajax表单提交
	public void login2(RequestContext rc) throws Exception {
		String uname = rc.param("uname");
		String passwd = rc.param("passwd");
		System.out.println(uname + ", " + passwd);
		
		// 返回数据JSON: {} --> map, [] --> list
		Map<String, Object> map = new LinkedHashMap<>();
		map.put("success", true);
		map.put("msg", "验证成功!");
		map.put("name", uname);
		
		String json = Jackson.me().toJson(map);
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 列出所有的数据字典: ajax
	 * */
	public void listDict(HttpServletRequest req, HttpServletResponse resp) {
		String sql = "select * from dictionary";
		List<Dictionary> list = QueryHelper.query(Dictionary.class, sql);
		
		String json = Jackson.me().toJson(list);
		ResponseUtils.renderJson(resp, json);
	}
	
	/**
	 * 列出所有的数据字典: 非ajax方式
	 * */
	public void listDict2(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String sql = "select * from dictionary";
		List<Dictionary> list = QueryHelper.query(Dictionary.class, sql);
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("/success.jsp").forward(req, resp);
	}
}
